from .serializers import InformSerializer,ReadInformSerializer
from .models import Inform,InformRead
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
from django.db.models import Q
from apps.absent.page import MyModelPagination
from django.db.models import Prefetch

#通知列表
class InformView(viewsets.ModelViewSet):
    queryset = Inform.objects.all()
    serializer_class = InformSerializer
    pagination_class = MyModelPagination
    def get_queryset(self):
        # 如果多个条件并查询，则需要使用Q查询
        #查询通知条件：公开的通知、允许自己部门查看的通知、自己写的通知
        # 返回reads判断是否已读
        queryset = self.queryset.prefetch_related(
            Prefetch("reads", queryset=InformRead.objects.filter(user=self.request.user))).filter(
            Q(public=True)|Q(department=self.request.user.department)|Q(author=self.request.user)).distinct() #distinct去重
        return queryset
        # for inform in queryset:
        #     inform.is_read = InformRead.objects.filter(user=self.request.user,inform=inform).exists()
    def list(self, request, *args, **kwargs):
        result = self.get_queryset()
        # paginate_queryset方法会做分页的逻辑处理
        page = self.paginate_queryset(result)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            data = serializer.data
            # get_paginated_response除了返回序列化的数据外，还会返回总数据，以及上一页的数据
            return self.get_paginated_response(data)
        serializer = self.get_serializer(result, many=True)
        return Response(serializer.data)

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        if instance.author.id != request.user.id:
            return Response({"detail": "您没有权限删除这条通知"}, status=status.HTTP_403_FORBIDDEN)
        self.perform_destroy(instance)
        return Response(status=status.HTTP_204_NO_CONTENT)
    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        data = serializer.data
        data["read_count"] = InformRead.objects.filter(inform_id=instance.id).count()
        return Response(data)


# 标记通知已读
class ReadInformView(APIView):
    def post(self, request):
        serializer = ReadInformSerializer(data=request.data)
        if serializer.is_valid():
            inform_pk = serializer.validated_data.get("inform_pk")
            if InformRead.objects.filter(user_id=request.user.id, inform_id=inform_pk).exists():
                return Response()
            else:
                try:
                    InformRead.objects.create(user_id=request.user.id, inform_id=inform_pk)
                except Exception as e:
                    return Response({"detail": "阅读失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                return Response({"detail": "阅读成功"}, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)



